#!/usr/bin/env python
# Batch system directives
{{ batchdirectives }}

"""
template to create a case run script. This should only ever be called
by case.submit when on batch system. This script only exists as a way of providing
batch directives. Use case.submit from the command line to run your case.

DO NOT RUN THIS SCRIPT MANUALLY
"""

import os, sys
os.chdir( '{{ caseroot }}')

_LIBDIR = os.path.join("{{ cimeroot }}", "scripts", "Tools")
sys.path.append(_LIBDIR)

from standard_script_setup          import *

from CIME.case import Case

logger = logging.getLogger(__name__)

import argparse

###############################################################################
def parse_command_line(args, description):
###############################################################################
    parser = argparse.ArgumentParser(description=description,
                                     formatter_class=argparse.RawTextHelpFormatter)

    CIME.utils.setup_standard_logging_options(parser)

    parser.add_argument("--caseroot",
                        help="Case directory to build")

    parser.add_argument("--skip-preview-namelist", action="store_true",
                        help="Skip calling preview-namelist during case.run")

    parser.add_argument("--completion-sets-continue-run", action="store_true",
                        help="This is used to ensure CONTINUE_RUN is cleared for an initial run, "
                        "but set for subsequent runs.")

    parser.add_argument("--resubmit", default=False, action="store_true",
                        help="If RESUBMIT is set, this performs the resubmissions.")

    args = CIME.utils.parse_args_and_handle_standard_logging_options(args, parser)

    if args.caseroot is not None:
        os.chdir(args.caseroot)

    if args.skip_preview_namelist is None:
        args.skip_preview_namelist = False

    return args.caseroot, args.skip_preview_namelist, args.completion_sets_continue_run, args.resubmit

###############################################################################
def _main_func(description):
###############################################################################
    sys.argv.extend([] if "ARGS_FOR_SCRIPT" not in os.environ else os.environ["ARGS_FOR_SCRIPT"].split())

    caseroot, skip_pnl, set_continue_run, resubmit = parse_command_line(sys.argv, description)
    with Case(caseroot, read_only=False) as case:
        success = case.case_run(skip_pnl=skip_pnl, set_continue_run=set_continue_run, submit_resubmits=resubmit)

    sys.exit(0 if success else 1)

if __name__ == "__main__":
    _main_func(__doc__)
